import React, { createContext, useState, useContext, useEffect } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { router } from "expo-router";
import { authAPI } from "@/services/api";

// 定义匹配偏好类型
type MatchPreferences = {
  preferredGender?: string;
  minAge?: number;
  maxAge?: number;
  minHeight?: number;
  maxHeight?: number;
  preferredEducation?: string[];
  preferredOccupations?: string[];
  preferredDistance?: number;
};

// 定义用户信息类型
type UserInfo = {
  id?: number;
  name: string;
  age: string;
  email: string;
  location?: string;
  gender?: string;
  height?: number;
  weight?: number;
  education?: string;
  occupation?: string;
  income?: string;
  bio?: string;
  maritalStatus?: string;
  hasChildren?: boolean;
  wantsChildren?: boolean;
  smoking?: string;
  drinking?: string;
  diet?: string;
  hasPets?: boolean;
  pets?: string[];
  interests?: string[];
  hobbies?: string[];
  values?: string[];
  religion?: string;
  politicalView?: string;
  relationshipGoal?: string;
  languages?: string[];
  matchPreferences?: MatchPreferences;
};

// 定义认证上下文的类型
type AuthContextType = {
  isLoading: boolean;
  userToken: string | null;
  userInfo: UserInfo | null;
  login: (email: string, password: string) => Promise<boolean>;
  register: (
    name: string,
    age: string,
    email: string,
    password: string
  ) => Promise<boolean>;
  logout: () => void;
  updateProfile: (updatedInfo: Partial<UserInfo>, preferences: any) => Promise<boolean>;
  changePassword: (
    currentPassword: string,
    newPassword: string
  ) => Promise<boolean>;
  getProfile: () => Promise<boolean>;
};

// 创建认证上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 定义认证提供者组件
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const [isLoading, setIsLoading] = useState(true);
  const [userToken, setUserToken] = useState<string | null>(null);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);

  // 初始化时检查存储的token和用户信息
  useEffect(() => {
    const bootstrapAsync = async () => {
      try {
        // 从存储中获取token和用户信息
        const token = await AsyncStorage.getItem("userToken");
        const userInfoStr = await AsyncStorage.getItem("userInfo");

        if (token) {
          setUserToken(token);
        }

        if (userInfoStr) {
          const parsedUserInfo = JSON.parse(userInfoStr);
          setUserInfo(parsedUserInfo);
        }
      } catch (e) {
        console.error("Failed to load data from storage", e);
      } finally {
        setIsLoading(false);
      }
    };

    bootstrapAsync();
  }, []);

  // 登录方法
  const login = async (email: string, password: string): Promise<boolean> => {
    setIsLoading(true);
    try {
      // 调用后端API进行登录
      const response = await authAPI.login(email, password);
      
      console.log("登录API响应:", response);
      
      // 检查响应中是否包含预期的数据
      if (!response || !response.access_token || !response.user) {
        console.error("登录响应缺少必要数据:", response);
        return false;
      }

      // 获取token和用户信息
      const token = response.access_token;
      const userData = response.user;

      console.log("保存用户数据:", userData);
      console.log("保存token:", token);

      // 保存token和用户信息
      await AsyncStorage.setItem("userToken", token);
      await AsyncStorage.setItem("userInfo", JSON.stringify(userData));

      console.log('用户信息保存到AsyncStorage:', userData);
      setUserToken(token);
      setUserInfo(userData);
      console.log("登录成功，用户信息已设置");
      return true;
    } catch (error: any) {
      console.error("Login error:", error);
      console.error("错误详情:", error.response?.data || error.message);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // 注册方法
  const register = async (
    name: string,
    age: string,
    email: string,
    password: string
  ): Promise<boolean> => {
    console.log('AuthContext: 开始注册过程', { name, email });
    setIsLoading(true);
    try {
      // 调用后端API进行注册
      console.log('AuthContext: 调用 authAPI.register');
      const response = await authAPI.register(name, age, email, password);
      console.log('AuthContext: 注册成功，响应:', response);
      return true;
    } catch (error: any) {
      console.error("AuthContext: 注册错误:", error);
      console.error("AuthContext: 错误详情:", error.response?.data || error.message);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // 登出方法
  const logout = async () => {
    setIsLoading(true);
    try {
      await AsyncStorage.removeItem("userToken");
      await AsyncStorage.removeItem("userInfo");
      setUserToken(null);
      setUserInfo(null);
      // 添加路由跳转到登录页面
      router.replace('/auth/login');
    } catch (e) {
      console.error("Logout error:", e);
    } finally {
      setIsLoading(false);
    }
  };

  // 获取用户资料
  const getProfile = async (): Promise<boolean> => {
    setIsLoading(true);
    try {
      const response = await authAPI.getProfile();
      console.log("获取到用户资料:", response.data);
      setUserInfo(response.data);
      return true;
    } catch (error: any) {
      console.error("获取用户资料错误:", error);
      console.error("错误详情:", error.response?.data || error.message);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // 更新个人资料方法
  const updateProfile = async (
    updatedInfo: Partial<UserInfo>,
    preferences: any = null
  ): Promise<boolean> => {
    setIsLoading(true);
    try {
      if (userInfo) {
        console.log("开始更新用户资料:", { userId: userInfo.id, updatedInfo, preferences });
        // 调用后端API更新个人资料
        const response = await authAPI.updateProfile(
          userInfo.id as number,
          updatedInfo,
          preferences
        );
        console.log("用户资料更新成功:", response.data);
        const updatedUserInfo = response.data;

        // 更新本地存储
        await AsyncStorage.setItem("userInfo", JSON.stringify(updatedUserInfo));
        setUserInfo(updatedUserInfo);
        return true;
      }
      return false;
    } catch (error: any) {
      console.error("更新用户资料错误:", error);
      console.error("错误详情:", error.response?.data || error.message);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  // 修改密码方法
  const changePassword = async (
    currentPassword: string,
    newPassword: string
  ): Promise<boolean> => {
    setIsLoading(true);
    try {
      if (userInfo) {
        // 调用后端API修改密码
        await authAPI.changePassword(
          userInfo.id as number,
          currentPassword,
          newPassword
        );
        return true;
      }
      return false;
    } catch (error) {
      console.error("Change password error:", error);
      return false;
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <AuthContext.Provider
      value={{
        isLoading,
        userToken,
        userInfo,
        login,
        register,
        logout,
        updateProfile,
        changePassword,
        getProfile,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

// 自定义钩子，用于在组件中访问认证上下文
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider");
  }
  return context;
};
